# -*- coding: utf-8 -*-
import os,sys,getopt,uuid,shutil,datetime,zipfile,time
from os.path import join  
from FileItem import FileItem
from FtpClient import FtpClient
from Config import Config

def main(argv):
    try:
        opts,args=getopt.getopt(argv,"f:d:o:tr:b:",["ftp=","dir=","opt=","tmp","remote=","bak=="])
    except getopt.GetoptError:          
        usage()                         
        sys.exit(2)
    host,port,user,pwd='',21,'',''
    tmp,local,remotedir,bak=os.path.dirname(__file__),'','./' ,''
    o=''
    print opts
    for opt,arg in opts:
        if opt in ['-f','--ftp']:
            cfg=Config(arg)
            host=cfg.str('host')
            port=cfg.int('port',21)
            user=cfg.str('user')
            pwd=cfg.str('pwd')
        elif opt in ['-o','--opt']:
            o=arg
        elif opt in ['-d','--dir']:
            local=arg
        elif opt in ['-t','--tmp']:
            tmp=arg
        elif opt in ['-r','--remote']:
            remotedir=arg
        elif opt in ['-b','--bak']:
            bak=arg
        else:
            print u'未知参数:'+opt
            usage()                         
            sys.exit(2)

    if o not in ['down','up']:
        print u'-o/--opt参数不正确。',o
        usage()                         
        sys.exit(2)
    ftp_args={'host':host,'port':port,'user':user,'pwd':pwd}
    client=FtpClient(**ftp_args)
    client.login()
    if o == 'down':
        down(client,remotedir,local,tmp)
    else:
        up(client,local,remotedir,bak,ftp_args)
    sys.exit(0)

def down(ftp,remotedir,local,tmp):
    ftp.cwd(remotedir)
    files=ftp.list()
    for file in files:
        if not file.endswith('.zip'):
            continue
        rfile=file.split()[-1]
        tmpfile=os.path.join(tmp,rfile)
        print tmpfile
        ftp.download_file(tmpfile,rfile)
        zip=FileItem(tmpfile)
        zip.exactto(local)
        zip.delete()


def up(ftp,local,remotedir,bak,ftp_args):
    print 'up'
    ftp.cwd(remotedir)
    files=ftp.list()
    for file in files:
        if file.endswith('.zip'):
            ftp.del_file(file.split()[-1])             #清除服务器文件
            print 'DEL',file
    ftp.close()
    #remote=str(uuid.uuid1()).replace('-','')+'.zip'
    f=FileItem(local)
    zippath=os.path.join(bak,'delta.zip')
    if not os.path.exists(zippath):
        try:
            f.zipto(zippath)
            print 'compress success'
        except Exception,e:
            print str(e)
            pass
    #重新登录
    ftp=FtpClient(**ftp_args)
    ftp.login()
    ftp.cwd(remotedir)
    now=datetime.datetime.now()
    bakfile=str(now).replace('-','').replace(':','').replace('.','').replace(' ','') + '.zip'
    remote=bakfile
    retry=0
    is_upload_ok=False
    while retry<=10:
        try:
            is_upload_ok=ftp.upload_file(zippath,remote)
            if is_upload_ok:
                break;
            else:
                ftp.del_file(remote)
        except Exception,e:
            print str(e)
            time.sleep(3)
        retry=retry+1
    ftp.close()
    #for delf in delfiles:
    #    delfItem=FileItem(delf)
    #    delfItem.delete()
    if is_upload_ok:
        print 'upload success'
        print 'start delete files'
        zip=zipfile.ZipFile(zippath,'r')
        p=os.path.dirname(local)
        for info in zip.infolist():
            fn=info.filename.replace('/','\\')
            delf=os.path.join(p,fn)
            if os.path.isfile(delf):
                os.remove(delf)
                print 'delete ',delf
            else:
                try:
                    os.rmdir(delf)
                    print 'delete ',delf
                except:
                    pass
        zip.close()
        #now=datetime.datetime.now()
        #bakfile=str(now).replace('-','').replace(':','').replace('.','').replace(' ','') + '.zip'
        bakfile=os.path.join(bak,bakfile)
        print 'rename %s to %s' %(zippath,bakfile)
        os.rename(zippath,bakfile)
        print 'delete files end'
    else:
        print 'upload fail'

def  usage():
    print u'使用说明'

main(sys.argv[1:])
